package com.ylyq.ylxx;

import cn.novelweb.video.edit.VideoEditing;
import cn.novelweb.video.pojo.VideoParameters;
import com.ylyq.ylxx.util.Tools;
import org.junit.platform.commons.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName FfmpegUtil
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/9/3 18:04
 * @Version 1.0
 */
public class FfmpegUtil {
    /**
     * 合并视频文件
     * @param videoPathList
     */
    public static void mergeVideo(List<String> videoPathList) {

        if (videoPathList.size() > 1){

//            String ffmpegPath = CaptureConfig.getFfmpegPath();// 此处是配置地址，可自行写死如“D:\\ffmpeg\\ffmpeg.exe”
            String ffmpegPath = "C:\\ffmpeg.exe";// 此处是配置地址，可自行写死如“D:\\ffmpeg\\ffmpeg.exe”
            String txtPath = "";
            try {
                int index = videoPathList.get(0).lastIndexOf(".");
//                String newMergePath = videoPathList.get(0).substring(0, index) + "new" + videoPathList.get(0).substring(index, videoPathList.get(0).length());
                String newMergePath ="D:\\temp\\" + Tools.getCurrentDate()+videoPathList.get(0).substring(index, videoPathList.get(0).length());
                txtPath = videoPathList.get(0).substring(0, index) + ".txt";
                FileOutputStream fos = new FileOutputStream(new File(txtPath));
                for (String path : videoPathList){
                    fos.write(("file '" + path + "'\r\n").getBytes());
                }
                fos.close();

                StringBuffer command = new StringBuffer("");
                command.append(ffmpegPath);
                command.append(" -f");
                command.append(" concat");
                command.append(" -safe");
                command.append(" 0");
                command.append(" -i ");
                command.append(txtPath);
                command.append(" -c");
                command.append(" copy ");// -c copy 避免解码，提高处理速度
                command.append(newMergePath);

                start(command.toString());

                // 删除产生的临时用来存放每个视频文件路径的txt文件
                File txtFile = new File(txtPath);
                txtFile.delete();

                // 删除原视频文件
//                for (String filePath : videoPathList){
//                    File file = new File(filePath);
//                    file.delete();
//                }

                // 合成的新视频文件重命名为原视频文件的第一个文件名
                File newFile = new File(newMergePath);
//                File oldFile = new File(videoPathList.get(0));
//                newFile.renameTo(oldFile);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void start(String command){
        try {
            final Process process = Runtime.getRuntime().exec(command);
            //⚠️此处代码是因为如果合并大视频文件会产生大量的日志缓存导致线程阻塞，最终合并失败，所以加两个线程处理日志的缓存，之后再调用waitFor方法，等待执行结果。
            new Thread(){
                @Override
                public void run (){
                    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line = null;
                    try {
                        while ((line = in.readLine()) != null){
                            System.out.println("output:" + line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            new Thread(){
                @Override
                public void run (){
                    BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line = null;
                    try {
                        while ((line = err.readLine()) != null){
                            System.out.println("err:" + line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            err.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            // 等待命令子线程执行完成
            process.waitFor();
            process.destroy();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {

        long begin = System.currentTimeMillis();

        // 合并视频文件
        List videoPathList = new ArrayList<>();
        videoPathList.add("D:\\temp\\mmm.mp4");
        videoPathList.add("D:\\temp\\123.mp4");
        videoPathList.add("D:\\temp\\999.mp4");
        videoPathList.add("D:\\temp\\20200803134725下载.mp4");
        videoPathList.add("D:\\temp\\20200803154935f045e17526098dd7e07d240df14b13c4.mp4");
        mergeVideo(videoPathList);
//        VideoParameters
//        VideoEditing.
        long end = System.currentTimeMillis();
        System.out.println(end - begin);
    }

}
